package com.lhy.admin.service;

import com.github.pagehelper.PageHelper;
import com.lhy.admin.model.User;
import com.lhy.admin.util.StringUtil;
import com.lhy.commonweb.model.Page;
import com.lhy.commonweb.service.AbstractService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.List;

@Service
public class UserService extends AbstractService<User, Integer> {

    public UserService(@Qualifier("userMapper") Mapper<User> mapper) {
        super(mapper);
    }

    public User getUserByNameOrEmailOrPhone(String cond) {
        Example example = new Example(User.class);
        example.createCriteria().orEqualTo(User.FieldEnum.NAME.javaFieldName(), cond)
                .orEqualTo(User.FieldEnum.EMAIL.javaFieldName(), cond)
                .orEqualTo(User.FieldEnum.PHONE.javaFieldName(), cond);
        example.and().andEqualTo(User.FieldEnum.STATUS.javaFieldName(), 1);
        List<User> users = mapper.selectByExample(example);
        if (users.size() == 0) {
            return null;
        }
        return users.get(0);
    }

    public User login(String cond, String password) {
        User user = getUserByNameOrEmailOrPhone(cond);
        if (user == null) {
            return null;
        }
        String s = StringUtil.md5(password, user.getName());
        boolean b = s.equalsIgnoreCase(user.getPass());
        if (b) {
            return user;
        }
        return null;
    }

    @Override
    public Page<User> query(Integer pageNumber, Integer pageSize, String sortColumns, User bean) {
        com.github.pagehelper.Page<Object> startPage = PageHelper.startPage(pageNumber, pageSize, sortColumns);
        Example example = new Example(User.class);
        if (!StringUtil.isEmpty(bean.getName())) {
            example.and().orLike(User.FieldEnum.NAME.javaFieldName(), "%" + bean.getName() + "%")
                    .orLike(User.FieldEnum.EMAIL.javaFieldName(), "%" + bean.getName() + "%")
                    .orLike(User.FieldEnum.PHONE.javaFieldName(), "%" + bean.getName() + "%");
        }
        if (bean.getDepartmentId() != null) {
            example.and().andEqualTo(User.FieldEnum.DEPARTMENT_ID.javaFieldName(), bean.getDepartmentId());
        }
        List<User> select = this.mapper.selectByExample(example);
        return new Page<>(pageNumber, pageSize, (new BigDecimal(startPage.getTotal())).intValue(), select);
    }
}
